package com.lucy.viewer.controller;

import cn.hutool.core.io.file.FileNameUtil;
import cn.hutool.core.lang.Validator;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.URLUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.http.Header;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import com.lucy.viewer.config.PreviewModeConfig;
import com.lucy.viewer.constant.ViewerConst;
import com.lucy.viewer.event.FileStoredEvent;
import com.lucy.viewer.params.ViewerFile;
import com.lucy.viewer.service.PreviewService;
import com.lucy.viewer.utils.ViewerFileCache;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author kindear
 * 文档预览服务
 */
@Slf4j
@Controller
@RequestMapping("viewer")
@Api(tags = "文档预览服务")
public class PreviewController {
    @Autowired
    PreviewModeConfig previewModeConfig;

    @Autowired
    PreviewService previewService;

    @Resource
    ApplicationContext context;

    @GetMapping("preview/{documentKey}")
    @ApiOperation(value = "文档预览",notes = "支持office文档和pdf,txt等")
    public ModelAndView previewFile(@PathVariable(value = "documentKey") String documentKey, HttpServletResponse response) throws IOException {
        // 获取渲染文件信息
        return previewService.loadPreviewView(documentKey,response);
    }

//    @GetMapping("preview/browser/{documentKey}")
//    @ApiOperation(value = "文档预览(浏览器)",notes = "")
//    public void previewBrowser(@PathVariable(value = "documentKey") String documentKey, HttpServletResponse response){
//
//    }

//    @GetMapping("md")
//    @ApiOperation(value = "MD文档预览",notes = "支持office文档和pdf,txt等")
//    public ModelAndView viewerMd() throws IOException {
//        ModelAndView modelAndView = new ModelAndView();
//        modelAndView.setViewName("mdeditor");
//        ViewerFile viewerFile = new ViewerFile();
//        viewerFile.setTitle("测试图片");
//        viewerFile.setUrl("https://www.dowebok.com/demo/192/img/thumbnails/tibet-1.jpg");
//        modelAndView.addObject("file",viewerFile);
//        return modelAndView;
//    }

    @RequestMapping("preview/remote")
    @ApiOperation(value = "网络文档预览",notes = "支持各种类型文档")
    public ModelAndView previewRemote(@RequestParam("url") String url,HttpServletResponse servletResponse) throws IOException {
        String baseDir = ViewerConst.tempFilePath();
        HttpResponse response = HttpRequest.get(url).execute();
        log.info(response.headers().toString());
        String fileNameHeader = response.header(Header.CONTENT_DISPOSITION);
        log.info(fileNameHeader);
        String contentType = response.header(Header.CONTENT_TYPE);
        log.info(contentType);
        String fileName = url;
        if (contentType.equals("application/octet-stream")){
            fileName = StringUtils.substringAfterLast(fileNameHeader,"=");
            fileName = URLUtil.decode(fileName);
            if (Validator.isNotEmpty(fileName)){
                fileName = fileName.replace("UTF-8''", "");
            }
        }else if (contentType.startsWith("image")){
            // 图片
             fileName = StringUtils.substringAfterLast(url,"/");
        }else {
            fileName = StringUtils.substringAfterLast(fileNameHeader,"=");
            fileName = URLUtil.decode(fileName);
            if (Validator.isNotEmpty(fileName)){
                fileName = fileName.replace("UTF-8''", "");
            }
        }
        ViewerFile viewerFile = new ViewerFile();
        // 计算md5 值
        String md5 = SecureUtil.md5(response.bodyStream());
        // 赋值md5
        viewerFile.setMd5(md5);
        // 随机key
        String key = IdUtil.fastSimpleUUID();
        // 打印
        log.info("文件key:{}",key);

        viewerFile.setKey(key);
        // 设置标题
        viewerFile.setTitle(fileName);
        // 设置文件名
        viewerFile.setFileName(fileName);
        // 设置文件类型
        String fileType = FileNameUtil.extName(fileName);
        viewerFile.setFileType(fileType);
        // 获取文件路径
        String filePath = baseDir + key + '.' + fileType;
        viewerFile.setPath(filePath);
        // 写入
        response.writeBody(filePath);
        // 文件访问链接
        viewerFile.setUrl("/viewer/download/"+key);
        // 写入文件缓存
        ViewerFileCache.put(key,viewerFile);
        // 发布事件
        context.publishEvent(new FileStoredEvent(this,viewerFile));
        // 加载预览方法
        return previewService.loadPreviewView(key,servletResponse);
    }
}
